package com.example.ch3;

import java.sql.ResultSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 将ActionForm强制类型转换为LoginForm
		LoginForm loginForm = (LoginForm)form;
		// 从ActionForm中解析出请求参数: username
		String userName = loginForm.getUserName();
		// 从ActionForm中解析出请求参数: password
		String pass = loginForm.getPassWord();
		String errMsg = "";
		//finish server check
		if(userName == null || userName.equals(""))
			errMsg += "您的用户名丢失或没有输入，请重新输入";
		else if(pass == null || pass.equals(""))
			errMsg += "您的密码丢失或没有输入，请重新输入";
		else {
			try {
				DbDao dd = DbDao.instance("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/test", "root", "55555");
				ResultSet rs = dd.query("select password from user_table where name='" + userName + "'");
				if(rs.next()) {
					if(rs.getString("password").equals(pass)) {
						HttpSession session = request.getSession();
						session.setAttribute("name", userName);
						return mapping.findForward("welcome");
					} else {
						errMsg += "您的用户名密码不符合，请重新输入";
					}
				} else {
					errMsg += "您的用户名不存在，请先注册";
				}
			} catch(Exception e) {
				request.setAttribute("exception", "业务异常");
				return mapping.findForward("error");
			}
			
		}
		if(errMsg != null && !errMsg.equals("")) {
			request.setAttribute("err", errMsg);
			return mapping.findForward("login");
		} else {
			// 否则跳转到welcome
			return mapping.findForward("welcome");
		}
	}
	
}
